class Admins::AccountsController < Admins::BaseController

  def show
    @user = User.find(params[:id])
    ability_cancan!
  end


  def edit
    @user = User.find(params[:id])
    ability_cancan!    
  end

  def update    
    @user = User.find(params[:id])
    ability_cancan!
    respond_to do |format|
      if @user.update_attributes(params[:user].permit(:department_id, :office_phone, :mobile,:name,:login,:email))
        if params[:user][:group]
          groups = params[:user][:group] || []
          @user.group_users.destroy_all
          groups.each do |group_id|
            @user.group_users.create(group_id: group_id)
          end
        end
        flash[:notice] ="信息更新完成"
        format.html{ redirect_to '/admins/news' }
      else
        flash[:notice] = @user.errors.full_messages.join(",")
        format.html{ render action: "edit" }
      end
    end
  end

  def new 
    authorize! :manage, User 
    @user = User.new  
  end

  def create
    authorize! :manage, User
    options = params[:user].permit(:department_id, :office_phone, :mobile, :name, :password, :password_confirmation, :email, :login)
    @user = User.create(options)
    respond_to do |format|
      if @user.valid?
        groups = params[:user][:group] || []
        groups.each do |group_id|
          @user.group_users.create(group_id: group_id)
        end
        format.html{ redirect_to admins_account_path(@user) }
      else
        flash[:notice] = @user.errors.full_messages.join(",")
        format.html{ render action: "new" }
      end
    end
  end

  def update_password
    @user = User.find(params[:id])
    respond_to do |format|
      if @user.update_attributes(params[:user].permit(:password, :password_confirmation))
        format.json{ head :no_content }
      else
        format.json{ render :json => @user.errors.full_messages, :status => 403 }
      end
    end
  end

  private 

  def ability_cancan!
    authorize! :manage, User unless @user == current_user
  end


end
